<?php

class DB {

	private $handle = null;
	private static $instance = null;
	public $name;

	private function __construct($dbName, $method = 'open') {
		$path = ROOT . '/../../sqlite/' . $dbName . '.db';

		if ($method == 'open') {
			if (!file_exists($path)) {
				exit('db not exists!');
			}
		}

		if ($method == 'create') {
			if (file_exists($path)) {
				unlink($path);
			}
		}

		$this->handle = new Sqlite3($path);

		$this->handle->createFunction('now', 'sqliteNow');
		
		$this->name = $dbName;
	}

	public static function create($dbName) {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self($dbName, 'create');
		}

		return self::$instance;
	}

	public static function open($dbName) {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self($dbName);
		}

		return self::$instance;
	}

	public function query($sql,$mode = SQLITE3_ASSOC) {
		$data = array();
		if (($result = $this->handle->query($sql))) {
			while ($row = $result->fetchArray($mode)) {
				array_push($data, $row);
			}
		}

		return $data;
	}

	public function find($sql) {
		$data = $this->query($sql);
		return isset($data[0]) ? $data[0] : false;
	}

	public function exec($sql) {
		return $this->handle->exec($sql);
	}

	public function __destroy() {
		$this->handle->close();
	}

}